<template>
  <div>
    <div class="row-header">
      <el-form label-width="50px">
        <el-form-item label=" ">
          <el-select size="small" v-model="channelCompany" placeholder="请选择通道选择" style="width: 300px;"
                     @change="changeChannelCompany">
            <el-option v-for="company in dictOperatorNameSelect" :key="company.value" :label="company.label"
                       :value="company"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button type="shenda" size="small" icon="el-icon-search" @click="currentPage = 1 ; initData()">查询</el-button>
        <el-button type="shenda" size="small" icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
      </div>
    </div>
    <div class="split-line"></div>
    <div class="row-main">
      <el-button type="shenda" size="small" icon="el-icon-plus" @click="toAddAccount" v-has="'AddAccountPer'">新建
      </el-button>
      <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }"
                v-has="'accountDataPer'"
                :data="tableData" tooltip-effect="dark" class="row-main-table" @selection-change="handleSelectionChange"
                v-loading.fullscreen="tableLoading" element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column prop="id" label="通道id" align="center"></el-table-column>
        <el-table-column prop="accountName" label="通道名称" align="center"></el-table-column>
        <el-table-column prop="dictOperatorName" label="通道" align="center"></el-table-column>
        <el-table-column prop="operatorName" label="上游公司名称" align="center"></el-table-column>
        <el-table-column prop="userName" label="账号ID" align="center"></el-table-column>
        <el-table-column prop="apnId" label="apnId" align="center"></el-table-column>
        <el-table-column prop="dictReadStatusName" label="状态" align="center">
          <template slot-scope="scope">
            <div :style="{color:scope.row.dictReadStatus=='C_ENABLE'?'green':'red'}">
              {{ scope.row.dictReadStatusName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="更新原因" align="center"></el-table-column>
        <el-table-column prop="name" label="操作" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <div>
                <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="scope.row.dictReadStatus=='C_DISABLE'" v-has="'EditAccountNamePer'">
                  <el-button type="text" class="operation" @click="modifyStatus(scope.row.id,'C_ENABLE')">开启</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.dictReadStatus=='C_ENABLE'" v-has="'EditAccountNamePer'">
                  <el-button type="text" class="operation" @click="modifyStatus(scope.row.id,'C_DISABLE')">关闭
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item v-has="'EditAccountNamePer'">
                  <el-button type="text" class="operation" @click="toEditAccount(scope.row)">编辑</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-has="'EditAccountNamePer'">
                  <el-button type="text" class="operation" @click="checkAccountBalance(scope.row)">查看余额</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-has="'EditAccountNamePer'">
                  <el-button type="text" class="operation" @click="accountTest(scope.row.id)">测试通道</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-has="'EditAccountNamePer'">
                  <el-button type="text" class="operation" @click="accountAct(scope.row.id)">通道操作</el-button>
                </el-dropdown-item>
                <!-- <el-button class="operation" style="width: 100%;" @click="updateStatus(row)" v-if="row.dictIsUsed==='C_YES'">禁用</el-button>
                <el-button class="operation" style="width: 100%;" @click="updateStatus(row)" v-if="row.dictIsUsed==='C_NO'">启用</el-button> -->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
          <!--          <template slot-scope="scope">-->
          <!--            <el-button class="operation" type="text" v-if="scope.row.dictReadStatus=='C_DISABLE'"-->
          <!--                       @click="modifyStatus(scope.row.id,'C_ENABLE')" v-has="'EditAccountNamePer'">开启-->
          <!--            </el-button>-->
          <!--            <el-button class="operation" type="text" v-if="scope.row.dictReadStatus=='C_ENABLE'"-->
          <!--                       @click="modifyStatus(scope.row.id,'C_DISABLE')" v-has="'EditAccountNamePer'">关闭-->
          <!--            </el-button>-->
          <!--            <el-button class="operation" type="text" @click="toEditAccount(scope.row)" v-has="'EditAccountNamePer'">编辑-->
          <!--            </el-button>-->
          <!--          </template>-->
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="row-main-pager"
                     :current-page.sync="currentPage" :page-size="pageSize"
                     layout="total,sizes,prev, pager, next, jumper"
                     :page-sizes="[10,20,50,100]" :total="total" background></el-pagination>

    </div>
    <el-dialog
      title="通道参数测试"
      :visible.sync="showTestDialog"
      :width="$store.state.app.screenWidth<992?'100%':'500px'"
      center>
      <el-form :model="form" ref="form" label-position="left">
        <el-form-item prop="cardNo" label="ICCID/卡号">
          <el-input v-model="form.iccid" placeholder="请输入待测试的iccid或卡号"/>
        </el-form-item>
        <el-form-item prop="requestUrl" label="接口URL" v-show="form.requestUrl">
          <span>{{ form.requestUrl }}</span>
        </el-form-item>
        <el-form-item prop="requestParams" label="入参" v-show="form.requestParams">
          <span>{{ form.requestParams }}</span>
        </el-form-item>
        <el-form-item prop="responseParams" label="回参" v-show="form.responseParams">
          <div style="max-height: 100px;overflow-y: scroll">
            <span>{{ form.responseParams }}</span>
          </div>
        </el-form-item>
        <el-form-item prop="requestParams" label="请求耗时" v-show="form.requestTime">
          <span>{{ form.requestTime }}</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <div style="font-size: 12px; color: #888;margin-bottom: 20px">*若当前通道不支持ICCID测试，请尝试更换卡号测试</div>
          <el-button @click="showTestDialog = false">取 消</el-button>
          <el-button type="primary" @click="doTestAccount" :loading="loading" v-preventReClick>确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog
      title="通道操作"
      :visible.sync="showAccountActDialog"
      :width="$store.state.app.screenWidth<992?'100%':'600px'"
      center>
      <el-form :model="form" ref="form" label-position="left" label-width="130px">
        <el-form-item prop="cardNo" label="轮询速度">
          <el-slider
            v-model="speed"
            :min="1"
            :max="10">
          </el-slider>
        </el-form-item>
        <el-form-item prop="requestUrl" label="重置缓存">
          <el-button type="warning" @click="doClearAccount">重置缓存</el-button>
          <div style="font-size: 12px; color: #888;margin-bottom: 20px">* <span v-if="time">您末次操作时间：{{ time }}，</span>通道清理缓存每两小时内仅能操作一次
          </div>
        </el-form-item>
        <el-form-item prop="requestUrl" label="打开或关闭复制ICCID">
          <el-button type="warning" @click="doDisplay('C_YES')">开启</el-button>
          <el-button type="warning" @click="doDisplay('C_NO')">关闭</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="showAccountActDialog = false">取 消</el-button>
          <el-button type="primary" @click="doAccountAct" :loading="loading" v-preventReClick>确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  clearAccountCache,
  getLastClearTime,
  updateAccountOperator,
  interfaceAccountConfiguration,
  updateAccountStatus,
  checkAccountBalance,
  interfaceAccountConfigurationTest,
  updateShowIccid,
} from '@/api/getData'

export default {
  name: 'AccountConfiguration',
  data() {
    return {
      maxPage: 1,
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableLoading: false,
      value: false,
      operatorName: '',
      soapUser: '',
      userName: '',
      dictOperator: '',
      dictStatusName: '',
      dictOperatorName: '',
      dictOperatorNameSelect: [],
      updateTime: '',
      balance: '',
      id: '',
      channelCompany: {},
      channelCompanyId: '',
      showTestDialog: false,
      loading: false,
      form: {
        iccid: '',
        requestParams: '',
        responseParams: '',
        requestUrl: '',
        requestTime: '',
      },
      pagekey: '',
      time: '',
      showAccountActDialog: false,
      speed: '5',
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      this.tableLoading = true;
      const returnData = await interfaceAccountConfiguration({
          channelCompanyId: this.channelCompanyId,
          dictOperator: this.dictOperator,
          page: {
            current: this.currentPage + '',
            size: this.pageSize + '',
            ascs: this.ascs,
            descs: this.descs
          }
        },
        {
          obj: this,
          key: 'tableLoading'
        })
      this.tableData = [];
      this.total = 0;
      this.dictOperatorNameSelect = []
      if (returnData._result) {
        returnData.data.channelCompany.forEach(item => this.dictOperatorNameSelect.push({
          value: item.id,
          label: item.operatorBranch,
          dictOperator: item.dictOperator
        }))
        returnData.data.page.records.map(item => {
          const obj = {}
          obj.id = item.id
          obj.channelCompanyId = item.channelCompanyId
          obj.dictOperatorName = item.dictOperatorName
          obj.operatorName = item.operatorName // 上游公司名称
          obj.soapUser = item.soapUser // 平台账号
          obj.userName = item.userName // API账号
          obj.updateTime = item.updateTime // 更新时间
          obj.unicomAccountID = item.unicomAccountID // API账号ID
          obj.key = item.key // key
          obj.kahaoPhone = item.kahaoPhone // API手机号
          obj.apnId = item.apnId // APNID
          obj.accountName = item.accountName
          obj.dictReadStatusName = item.dictReadStatusName;
          obj.reason = item.reason
          obj.dictReadStatus = item.dictReadStatus
          this.tableData.push(obj)
        });
        this.total = returnData.data.page.total;
        this.tableLoading = false
      }
    },
    changeChannelCompany(val) {
      this.channelCompany = val;
      this.channelCompanyId = val.value;
      this.dictOperator = val.dictOperator;
      // this.dictOperatorNameSelect.forEach(item => {
      //   if (item.id === this.channelCompanyId) {
      //     this.dictOperator = item.dictOperator
      //   }
      // })
    },
    toAddAccount() {
      this.$router.push({path: '/interface/add-account'})
    },
    toEditAccount(account) {
      this.$router.push(({path: `/interface/add-account`, query: {id: account.id}}))
    },
    async accountAct(id) {
      this.id = id;
      let res = await getLastClearTime({id: id});
      this.time = res._result ? res.data.lastUpdateCacheTime : '';
      this.speed = res._result ? res.data.aroundSpeed : '';
      this.showAccountActDialog = true;
    },
    async doAccountAct() {
      this.loading = true;
      let res = await updateAccountOperator({id: this.id, aroundSpeed: this.speed});
      if (res.code == 10000) {
        this.$message({
          type: 'success',
          message: '轮询速度更新成功'
        })
        this.showAccountActDialog = false;
      } else {
        this.$message.error('轮询速度更新失败')
      }
      this.loading = false;
    },
    async doDisplay(status) {
      let res = await updateShowIccid({id: this.id, dictDisplayIccid: status});
      if (res.code == 10000) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
      } else {
        this.$message.error('操作失败')
      }
    },
    async doClearAccount() {
      let res = await clearAccountCache({id: this.id});
      if (res.code == 10000) {
        this.$message({
          type: 'success',
          message: '缓存清理成功'
        })
        this.showAccountActDialog = false;
      } else {
        this.$message.error('缓存清理失败')
      }

    },
    async checkAccountBalance(row) {
      let res = await checkAccountBalance({id: row.id});

      if (res.data && res.data.code == 'success') {
        this.$alert(`您在${row.accountName}内的账户余额为：${res.data.money.toFixed(2)}元`, '查询余额', {
          confirmButtonText: '确定',
          callback: action => {

          }
        });
      }
      if (res.data && res.data.code != 'success') {
        this.$alert(`查询余额失败，${row.accountName}${res.data.msg}`, '查询余额', {
          confirmButtonText: '确定',
          callback: action => {

          }
        });
      }
      if (!res.data) {
        this.$alert(`查询余额失败，${row.accountName}不支持查询余额`, '查询余额', {
          confirmButtonText: '确定',
          callback: action => {

          }
        });
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initData();
    },
    modifyStatus(id, dictReadStatus) {
      updateAccountStatus({id, dictReadStatus}).then(v => {
        if (v._result) {
          this.$message.success("操作成功！")
          this.initData()
        } else {
          this.$message.error("操作失败！")
        }
      })
    },
    resetForm() {
      this.channelCompanyId = '';
      this.dictOperator = '';
      this.channelCompany = {};
    },
    async accountTest(id) {
      this.showTestDialog = true;
      this.form.iccid = '';
      this.form.requestParams = '';
      this.form.requestUrl = '';
      this.form.responseParams = '';
      this.form.requestTime = '';
      this.form.id = id;
      this.pagekey = await this.$getPageKey();
    },
    async doTestAccount() {
      if (!this.form.iccid) {
        this.$message.error('请输入待测试的iccid');
        return false;
      }
      let res = await interfaceAccountConfigurationTest({
        id: this.form.id,
        iccid: this.form.iccid,
        pagekey: this.pagekey
      })
      if (res._result) {
        if (res.data.code == 'success') {
          this.$message({
            type: 'success',
            message: '通道测试通过'
          })
          this.form.requestUrl = res.data.requestUrl;
          this.form.requestParams = res.data.requestParams;
          this.form.responseParams = res.data.responseData;
          this.form.requestTime = res.data.requestTime;
        } else {
          this.$message.error(res.data.msg)
        }
      }
    },
  }
}
</script>

<style scoped lang="scss">

.examine /deep/ .el-dialog__body {
  text-align: center;
  font-size: 14px;
  font-family: 微软雅黑;
  line-height: 40px;
  color: #606266;
  font-weight: 700;
}

.el-popper[x-placement^=bottom] {
  margin-right: -25px;
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;
}

.el-popper[x-placement^=top] {
  box-shadow: 0px 0px 10px #888888;
  margin-left: 6px;
  margin-right: -25px;

  button {
    display: block;
  }
}

.operation {
  width: 100%;
  height: 30px;
  line-height: 30px;
  border: 0;
  outline: none;
  display: block;
  text-align: center;
  margin: 0;
  padding: 0 17px;
}
</style>
